package com.example.service;

import cn.hutool.core.util.ObjectUtil;
import com.example.common.Constants;
import com.example.common.enums.ResultCodeEnum;
import com.example.common.enums.RoleEnum;
import com.example.entity.Account;
import com.example.entity.Student;
import com.example.exception.CustomException;
import com.example.mapper.StudentMapper;
import com.example.utils.TokenUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import jakarta.annotation.Resource;
import java.util.List;

/**
 * 学生业务处理
 **/
@Service
public class StudentService {

    @Resource
    private StudentMapper studentMapper;

    /**
     * 新增
     * 权限控制：只有管理员可以新增学生
     */
    public void add(Student student) {
        // 检查权限：只有管理员可以新增学生
        Account currentUser = TokenUtils.getCurrentUser();
        if (currentUser != null && !RoleEnum.ADMIN.name().equals(currentUser.getRole())) {
            throw new CustomException(ResultCodeEnum.NO_AUTH);
        }
        
        Student dbStudent = studentMapper.selectByUsername(student.getUsername());
        if (ObjectUtil.isNotNull(dbStudent)) {
            throw new CustomException(ResultCodeEnum.USER_EXIST_ERROR);
        }
        if (ObjectUtil.isEmpty(student.getPassword())) {
            student.setPassword(Constants.USER_DEFAULT_PASSWORD);
        }
        if (ObjectUtil.isEmpty(student.getName())) {
            student.setName(student.getUsername());
        }
        student.setRole(RoleEnum.STUDENT.name());
        studentMapper.insert(student);
    }

    /**
     * 删除
     * 权限控制：只有管理员可以删除学生
     */
    public void deleteById(Integer id) {
        // 检查权限：只有管理员可以删除学生
        Account currentUser = TokenUtils.getCurrentUser();
        if (currentUser != null && !RoleEnum.ADMIN.name().equals(currentUser.getRole())) {
            throw new CustomException(ResultCodeEnum.NO_AUTH);
        }
        
        studentMapper.deleteById(id);
    }

    /**
     * 批量删除
     */
    public void deleteBatch(List<Integer> ids) {
        // 使用 Java 21 增强的 Stream API
        ids.forEach(studentMapper::deleteById);
    }

    /**
     * 修改
     * 权限控制：学生只能修改自己的信息，管理员可以修改任何学生
     */
    public void updateById(Student student) {
        // 检查权限
        Account currentUser = TokenUtils.getCurrentUser();
        if (currentUser != null) {
            if (RoleEnum.STUDENT.name().equals(currentUser.getRole())) {
                // 学生只能修改自己的信息
                if (!student.getId().equals(currentUser.getId())) {
                    throw new CustomException(ResultCodeEnum.NO_AUTH);
                }
            } else if (RoleEnum.TEACHER.name().equals(currentUser.getRole())) {
                // 教师不能修改学生信息
                throw new CustomException(ResultCodeEnum.NO_AUTH);
            }
            // 管理员可以修改任何学生
        }
        
        studentMapper.updateById(student);
    }

    /**
     * 根据ID查询
     */
    public Student selectById(Integer id) {
        return studentMapper.selectById(id);
    }

    /**
     * 查询所有
     * 添加权限控制：学生可以查看同班同学的信息，教师和管理员可以查看所有学生
     */
    public List<Student> selectAll(Student student) {
        List<Student> list = studentMapper.selectAll(student);
        
        // 获取当前登录用户
        Account currentUser = TokenUtils.getCurrentUser();
        if (currentUser != null && RoleEnum.STUDENT.name().equals(currentUser.getRole())) {
            Student currentStudent = (Student) currentUser;
            // 学生可以看到同班同学的信息
            return list.stream()
                    .filter(s -> s.getClassId() != null && s.getClassId().equals(currentStudent.getClassId()))
                    .toList();
        }
        
        // 教师和管理员可以看到所有学生
        return list;
    }

    /**
     * 分页查询
     * 添加权限控制：学生可以查看同班同学的信息，教师和管理员可以查看所有学生
     */
    public PageInfo<Student> selectPage(Student student, Integer pageNum, Integer pageSize) {
        // 获取当前登录用户
        Account currentUser = TokenUtils.getCurrentUser();
        if (currentUser != null && RoleEnum.STUDENT.name().equals(currentUser.getRole())) {
            Student currentStudent = (Student) currentUser;
            // 学生只能看到同班同学的信息
            student.setClassId(currentStudent.getClassId());
        }
        
        PageHelper.startPage(pageNum, pageSize);
        List<Student> list = studentMapper.selectAll(student);
        return PageInfo.of(list);
    }

    /**
     * 登录
     */
    public Account login(Account account) {
        Account dbStudent = studentMapper.selectByUsername(account.getUsername());
        if (ObjectUtil.isNull(dbStudent)) {
            throw new CustomException(ResultCodeEnum.USER_NOT_EXIST_ERROR);
        }
        if (!account.getPassword().equals(dbStudent.getPassword())) {
            throw new CustomException(ResultCodeEnum.USER_ACCOUNT_ERROR);
        }
        // 生成token
        String tokenData = dbStudent.getId() + "-" + RoleEnum.STUDENT.name();
        String token = TokenUtils.createToken(tokenData, dbStudent.getPassword());
        dbStudent.setToken(token);
        return dbStudent;
    }

    /**
     * 注册
     */
    public void register(Account account) {
        Student student = new Student();
        BeanUtils.copyProperties(account, student);
        add(student);
    }

    /**
     * 修改密码
     */
    public void updatePassword(Account account) {
        Student dbStudent = studentMapper.selectByUsername(account.getUsername());
        if (ObjectUtil.isNull(dbStudent)) {
            throw new CustomException(ResultCodeEnum.USER_NOT_EXIST_ERROR);
        }
        if (!account.getPassword().equals(dbStudent.getPassword())) {
            throw new CustomException(ResultCodeEnum.PARAM_PASSWORD_ERROR);
        }
        dbStudent.setPassword(account.getNewPassword());
        studentMapper.updateById(dbStudent);
    }

}
